import { dialogConfig } from "@/config/dialogConfig";
import { addUser, editUser, UserListParmas } from "./../../api/user";
// 手机号验证
const phoneValid = (rule: any, value: any, callback: any) => {
  if (value == "" || !value) {
    callback(new Error("请输入手机号"));
  } else {
    const reg = /^1[3456789]\d{9}$/;
    if (!reg.test(value)) {
      callback(new Error("手机号格式不正确"));
    }
    callback();
  }
};
export const dConfig = (
  lineData: UserListParmas,
  isDialog: string,
  tableRef: any
) => {
  return dialogConfig({
    title: isDialog == "add" ? "添加用户" : "编辑用户",
    formConfig: {
      formItems: [
        {
          label: "用户名",
          prop: "username",
          type: "input",
          maxlength: 15,
          value: lineData.username,
          otherOptions: { placeholder: "请输入用户名" },
          rules: [{ required: true, trigger: "blur", message: "请输入用户名" }],
        },
        {
          label: "手机号",
          prop: "phone",
          type: "input",
          value: lineData.phone,
          disabled: isDialog == "edit",
          maxlength: 11,
          otherOptions: { placeholder: "请输入手机号" },
          rules: [
            {
              validator: phoneValid,
              required: true,
              trigger: "change",
            },
          ],
        },
      ],
      showSubmit: false,
    },

    submitRequest: async (props) => {
      if (isDialog == "add") {
        try {
          await addUser(props);
          tableRef.reload();
          ElMessage.success("添加成功");
        } catch (e) {
          ElMessage.error("添加失败");
        }
      }
      if (isDialog == "edit") {
        try {
          await editUser(props);
          tableRef.reload();
          ElMessage.success("编辑成功");
        } catch (e) {
          ElMessage.error("编辑失败");
        }
      }
    },
  });
};
